08. Lab II: Solution

Solution: Build a Dog REST API - Annotations Part I

Below, we'll walk through each step of the lab and look at one potential way to implement the lab. Even if you get stuck, you should always first try to work through the lab without the solution before coming here, so that you can best learn the related skills and be ready for the project at the end of the course.

Step 1: Create an entity called Dog.

  • The dog should have three attributes:
    • Name
    • Breed
    • Origin

First, create a new package in the same directory that holds your main application, called entity. Then, create a new Java class called Dog.

The below code could be used to implement such an entity with the required attributes. Note that you should also include constructors for the class, as well as accessors and mutators for the three attributes. Important: The package name may differ depending on what you used during the set up of your project - make sure to adjust it to apply to your own project structure!

package com.udacity.DogRestApi.entity;

import javax.persistence.*;

@Entity
public class Dog {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;
    private String breed;
    private String origin;

    public Dog(Long id, String name, String breed, String origin) {
        this.id = id;
        this.name = name;
        this.breed = breed;
        this.origin = origin;
    }

    public Dog(String name, String breed) {
        this.name = name;
        this.breed = breed;
    }

    public Dog() {}

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    public String getOrigin() {
        return origin;
    }

    public void setOrigin(String origin) {
        this.origin = origin;
    }
}

Step 2: Create a web controller using @RestController.

  • You just need to create the structure of the controller for now. You'll add more to it once we discuss services next.

First, create a new package in the same directory that holds your main application, called web. Then, create a new Java class called DogController.

The below code contains the first steps for this controller, which we will complete in the final lab of this lesson after implementing the related DogService.

package com.udacity.DogRestApi.web;

import org.springframework.web.bind.annotation.RestController;
// Note - we will eventually also import additional packages later on

@RestController
public class DogController {

}